package com.example.nettydemo.NIO.群聊系统;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class 客户端 {

    private final String HOST = "127.0.0.1";//服务器ip
    private final int PORT = 5438;//服务器端口
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    public 客户端 () {

        try {
            selector = Selector.open();//获取选择器
            socketChannel = SocketChannel.open(new InetSocketAddress(HOST,PORT));//链接服务器
            socketChannel.configureBlocking(false);//设置非阻塞
            socketChannel.register(selector, SelectionKey.OP_READ);
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(username + "启动");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        客户端 khd = new 客户端();//启动客户端
        new Thread(()->{
            while (true){
                khd.readInfo();
                try{ TimeUnit.SECONDS.sleep(1);}catch (InterruptedException e){e.printStackTrace();}
            }
        }).start();

        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String s = sc.nextLine();
            khd.sedInfo(s);
        }
    }

    public void sedInfo(String info) {
        info = username + "说：" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public void readInfo() {
        try {
            if(selector.select()>0){
                Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
                while (keys.hasNext()){
                    SelectionKey key = keys.next();
                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        channel.configureBlocking(false);//设置非阻塞
                        ByteBuffer allocate = ByteBuffer.allocate(1024);

                        channel.read(allocate);
                        String s = new String(allocate.array());
                        System.out.println(s.trim());

                    }
                    keys.remove();
                }
            }
        }catch (IOException e ){
            e.printStackTrace();
        }
    }
}
